package com.difsonapps.android.marker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.difsonapps.android.marker.activities.LoginActivity;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.Album;
import com.difsonapps.android.marker.beans.Photo;
import com.difsonapps.android.marker.util.MarkerUtil;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FormPhotoActivity extends Activity {
	private final int SELECT_PHOTO = 1;
	Album album;//Concerned album
	Photo photo; //Current selected Photo
	ImageView selectedImageView;
	TextView albumTextView;
	EditText titleEditText;
	EditText descriptionEditText;
	Button addPictureButton;
	Button publishButton;
	Button cancelButton;
	LinearLayout loadingStatusLayout;
	String currentUploadeFile = null;
	
	File currentSelectedFile=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_form_photo);

		Intent i = getIntent();
		album = i.getParcelableExtra("album");
		
		selectedImageView = (ImageView)findViewById(R.id.selectedImageView);
		albumTextView = (TextView)findViewById(R.id.albumValueTextView);
		titleEditText = (EditText)findViewById(R.id.titleEditText);
		descriptionEditText = (EditText)findViewById(R.id.descriptionEditText);
		
		addPictureButton = (Button)findViewById(R.id.addPictureButton);
		publishButton = (Button)findViewById(R.id.saveButton);
		cancelButton = (Button)findViewById(R.id.closeButton);
		loadingStatusLayout = (LinearLayout)findViewById(R.id.loadingStatusLayout);
		hideProgress();
		addPictureButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {				
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, SELECT_PHOTO);
			}
		});
		publishButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {				
				save();
			}
		});
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {				
				cancel();
			}
		});
		
	}
	
	private void showProgress(){
		loadingStatusLayout.setVisibility(View.VISIBLE);
	}
	
	private void hideProgress(){
		loadingStatusLayout.setVisibility(View.GONE);
	}
	

	 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
 
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){
				try {
					//showProgress();
					final Uri imageUri = imageReturnedIntent.getData();
					toast(imageUri.getPath());
					toast(getPath(imageUri));
					File file = new File(getPath(imageUri));
					if(file.exists()) currentSelectedFile = file;
					final InputStream imageStream = getContentResolver().openInputStream(imageUri);
					final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
					selectedImageView.setImageBitmap(selectedImage);
					//hideProgress();
					upload();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
 
            }
        }
    }

    public String getPath(Uri uri) {
    	String[] projection = { MediaStore.Images.Media.DATA };
    	Cursor cursor = managedQuery(uri, projection, null, null, null);
    	startManagingCursor(cursor);
    	int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    	cursor.moveToFirst();
    	return cursor.getString(column_index);
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.form_photo, menu);
		return true;
	}
	private void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	
	private void upload(){
		if(currentSelectedFile==null) {
			toast(getResources().getString(R.string.no_image_selected));
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
		/*String comment = markCommentEditText.getText().toString();
        params.put("id", ""+0);//TODO Put the id of the image selected here
        params.put("value", ""+valueSelected);
        params.put("description", comment);*/
		showProgress();
		UploadRequest jsObjRequest = new UploadRequest(
				AppConstant.uploadPhotoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonUpload(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                },
                currentSelectedFile
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void parseJsonUpload(JSONObject response){
		try {
        	//toast(response.toString());
            if(response.has("success")&&response.has("file")){
            	String success = response.getString("success");
            	toast(success);
            	String file = response.getString("file");
            	if(file!=null&&!file.trim().equals("")){
            		currentUploadeFile = file;
            		toast(getResources().getString(R.string.file_uploaded));
            	}else{
            		toast(getResources().getString(R.string.error_while_uploading));
            	}
            }else if(response.has("error")){
            	String error = response.getString("error");
            	//TODO Show the error message in a textView and make it visible
            	//loginErrorView.setText(error);
            	//loginErrorView.setVisibility(View.VISIBLE);
            	toast(error);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //hideProgress();
	}
	
	private void parseJsonSave(JSONObject response){
		try {
        	//toast(response.toString());
            if(response.has("success")&&response.has("photo")){
            	//String success = response.getString("success");
            	//toast(success);
            	JSONObject photoOject = response.getJSONObject("photo");
            	Photo photo = Photo.parseFromJsonObject(photoOject);
            	
            	if(photo!=null){
            		//Put the photo in the result of the parent activity
            		finish();
            	}else{
            		toast(getResources().getString(R.string.error_while_saving));
            	}
            }else if(response.has("error")){
            	String error = response.getString("error");
            	//TODO Show the error message in a textView and make it visible
            	//loginErrorView.setText(error);
            	//loginErrorView.setVisibility(View.VISIBLE);
            	toast(error);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //hideProgress();
	}
	
	private void save(){
		if(currentUploadeFile==null) {
			toast(getResources().getString(R.string.no_image_uploaded));
			return;
		}
		if(album==null) {
			toast(getResources().getString(R.string.no_album_selected));
			return;
		}
		Map<String, String> params = new HashMap<String, String>();
        params.put("album_id", ""+album.getId());//TODO Put the id of the image selected here
        params.put("name", ""+titleEditText.getText().toString());
        params.put("description", ""+descriptionEditText.getText().toString());
        params.put("image", currentUploadeFile);
		showProgress();
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.createPhotoUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	hideProgress();
                    	toast("Response : "+response.toString());
                    	Log.i("Test", response.toString());
                    	parseJsonSave(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	hideProgress();
                    	toast("Error: " + error.getMessage());
                    	Log.e("Test", error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	private void cancel(){
		this.finish();
	}

}
